package com.aijk.web.admin.controller.medical;

import com.aijk.commons.utils.Utils;
import com.aijk.medical.api.BasRegionApi;
import com.aijk.medical.api.MedResidentApi;
import com.aijk.medical.model.BasRegion;
import com.aijk.medical.model.MedResident;
import com.aijk.medical.model.qo.BasRegionQo;
import com.aijk.web.admin.config.WebConfig;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.Constant;
import com.aijk.web.admin.entity.KeyValues;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lifesea.commons.entity.RetMsg;
import com.lifesea.familydoctor.model.FdTeam;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/medical/resident")
public class MedResidentController extends BaseController{
    private static Logger logger = LoggerFactory.getLogger(MedResidentController.class);
    private static String hcc = HttpMethodParams.HTTP_CONTENT_CHARSET;

    @Autowired
    private BasRegionApi basRegionApi;

    @Autowired
    private MedResidentApi medResidentApi;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return "controller/list";
    }

    /*@RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg list(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Long draw) {
        Long iTotalRecords;
        MedRecordQo qo = DataTableUtil.fillQo(skey, MedRecordQo.class);
        PageInfo<MedRecord> pageInfo = medRecordApi.page(qo);
        iTotalRecords = pageInfo.getTotal();
        RetMsg retMsg = new RetMsg();
        retMsg.put("data", pageInfo.getList());
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }*/

    /**新增、编辑**/
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit_view(Model model, Integer id) {
        HttpSession session = request.getSession();
        FdTeam team = (FdTeam) session.getAttribute(Constant.SESSION_TEAM);
        MedResident bean = new MedResident();
        if (id != null){
//            bean = medResidentApi.findOne(id);
        }
        BasRegionQo qo = new BasRegionQo();
        qo.setPid(Constant.REGION_ID_NANJING);
        List<BasRegion> list = basRegionApi.list(qo);
        model.addAttribute("data", bean);
        model.addAttribute("team", team);
        model.addAttribute("districts", list);

        qo.setPid(Constant.REGION_ID_PUKOU);// 默认浦口区
        List<BasRegion> li = basRegionApi.list(qo);
        model.addAttribute("towns", li);

        List<KeyValues> keyValuesList = Constant.getPersonCategory();
        model.addAttribute("kv", keyValuesList);
        return "medical/resident/edit";
    }

    @RequestMapping(value = "/signCheck", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg signCheck(@RequestParam String idcard) {
        return medResidentApi.signCheck(idcard);
    }

    @RequestMapping(value = "/getChildRegions", method = RequestMethod.POST)
    @ResponseBody
    public List<BasRegion> getChildRegions(Integer regionId) {
        RetMsg retMsg = new RetMsg();
        BasRegionQo qo = new BasRegionQo();
        qo.setPid(regionId);
        List<BasRegion> list = basRegionApi.list(qo);
        return list;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg save(@RequestParam HashMap skey) {
        skey.put("city", Constant.REGION_NAME_NANJING);
        skey.put("city_id", Constant.REGION_ID_NANJING);
        skey.put("province", Constant.REGION_NAME_JIANGSU);
        skey.put("province_id", Constant.REGION_ID_JIANGSU);
        Integer districtId = Utils.toInteger(skey.get("district_id"));
        BasRegion district = basRegionApi.get(districtId);
        String districtTitle = (district != null) ? district.getTitle() : "";
        skey.put("district", districtTitle);
        Integer townId = Utils.toInteger(skey.get("town_id"));
        BasRegion town = basRegionApi.get(townId);
        String townTitle = (town != null) ? town.getTitle() : "";
        skey.put("town", townTitle);

        // 获取当前医生idcard
        HttpSession session = request.getSession();
        String doctorIdcard = (String) session.getAttribute(Constant.SESSION_IDCARD);
        skey.put("doctorIdcard", doctorIdcard);

        // 获取当前选择的团队
        FdTeam team = (FdTeam) session.getAttribute(Constant.SESSION_TEAM);
        skey.put("team", team);

        String images = skey.get("image1")+"|"+skey.get("image2");
        skey.put("voucherImages" , images);
        return medResidentApi.save(skey);
    }

    @RequestMapping(value = "/ehrCheck", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject ehrCheck(@RequestParam HashMap skey) {
        String idcard = String.valueOf(skey.get("idcard"));
        String ehrCheckUrl = WebConfig.COMMON.getValue("ehr_check");
        String result = ehrCheck(ehrCheckUrl, idcard);
        JSONObject object = JSON.parseObject(result);
        return object;
    }

    @RequestMapping(value = "/saveqyinfo", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveqyinfo(@RequestParam HashMap skey) {
        String sxsj = String.valueOf(skey.get("sxsj"));
        String zzsj = String.valueOf(skey.get("zzsj"));
        String idcard = String.valueOf(skey.get("idcard"));
        String ehrCheckUrl = WebConfig.COMMON.getValue("ehr_check");
        String result = saveqyinfo(ehrCheckUrl, idcard, sxsj, zzsj);
        JSONObject object = JSON.parseObject(result);
        return object;
    }

    private String ehrCheck(String url, String idcard) {
        HttpClient client = new HttpClient();
        String json = "{\"method\":\"execute\",\"serviceAction\":\"checkqyinfo\"," +
                "\"serviceId\":\"chis.mobileAppService\",\"idcard\":\""+ idcard +"\"}";

        PostMethod method = new PostMethod(url);
        HttpMethodParams params = method.getParams();
        params.setParameter(hcc, "utf-8");

        StringBuffer stringBuffer = new StringBuffer();
        try {
            method.setRequestHeader("Accept", "application/json");
            method.setRequestHeader("Content-Type", "application/json;charset=utf-8");
            method.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
            client.executeMethod(method);
            InputStream inputStream = method.getResponseBodyAsStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(isr);

            String str = "";
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 使用完成后要释放链接
        method.releaseConnection();
        return stringBuffer.toString();
    }

    private String saveqyinfo(String url, String idcard, String sxsj, String zzsj) {
        HttpClient client = new HttpClient();
        String json = "{\"method\":\"execute\"," +
                "\"serviceAction\":\"saveqyinfo\",\"serviceId\":\"chis.mobileAppService\"," +
                "\"data\":{\"idcard\":\""+ idcard +"\"," +
                "\"sxsj\":\""+ sxsj +"\",\"zzsj\":\""+ zzsj +"\"}}";

        PostMethod method = new PostMethod(url);
        HttpMethodParams params = method.getParams();
        params.setParameter(hcc, "utf-8");

        StringBuffer stringBuffer = new StringBuffer();
        try {
            method.setRequestHeader("Accept", "application/json");
            method.setRequestHeader("Content-Type", "application/json;charset=utf-8");
            method.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
            client.executeMethod(method);
            InputStream inputStream = method.getResponseBodyAsStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(isr);

            String str = "";
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 使用完成后要释放链接
        method.releaseConnection();
        return stringBuffer.toString();
    }

    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public @ResponseBody RetMsg edit(@RequestParam(value = "id", required = false, defaultValue = "0") Long id, Model model) {
        RetMsg retMsg = new RetMsg();
        /*MedRecord MedRecord = medRecordApi.findOne(id);
        retMsg.put("MedRecord", MedRecord);*/
        return retMsg;
    }

}